package pers.qianyu.month_202012.date_20201210;

import org.junit.*;

import java.util.*;

/**
 * 77. 组合
 * https://leetcode-cn.com/problems/combinations/
 *
 * @author mizzle rain
 * @date 2020-12-10 20:29
 */
public class Combine {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        ArrayList<Integer> track = new ArrayList<>();
        backTracking(track, n, k, 1);
        return res;
    }

    private void backTracking(ArrayList<Integer> track, int n, int k, int startIndex) {
        if (track.size() == k) {
            res.add(new ArrayList<>(track));
            return;
        }
        for (int i = startIndex; i <= n; i++) {
            // 剪枝 14ms 变成 2ms
            if (track.size() + (n - startIndex + 1) < k) {
                continue;
            }
            track.add(i);
            // 注意这里是 i + 1 ，而不是 start + 1 （从左往右，决策树越来越小）
            backTracking(track, n, k, i + 1);
            track.remove(track.size() - 1);
        }
    }

    @Test
    public void test1() {
        List<List<Integer>> result = new Combine().combine(4, 2);
        result.forEach(System.out::println);
    }
}
